package Modules.CommunicationsModule
{
	
	import Modules.MainTimeLine;
	import Modules.VolunteerModule.PlayerActivityJoin;
	
	import com.adobe.serialization.json.*;
	
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;

	public class PlayerActivityCommunications
	{
		public function PlayerActivityCommunications()
		{
		}
			
		// load list of activity which players joined
		public static function loadPlayerActivityJoin():void{
			
			MainTimeLine.loadedPlayerActivityJoin = false;
			
			var loader:URLLoader = new URLLoader();
			loader.dataFormat = URLLoaderDataFormat.TEXT;
			
			var activityPlayerRequest:URLRequest = new URLRequest("http://ft.nus-hci.com/PHP/volunteer/getPlayerActivityJoin.php");
			activityPlayerRequest.method = URLRequestMethod.POST;
			
			try{
				loader.load(activityPlayerRequest);
				loader.addEventListener(Event.COMPLETE, function(event:Event):void{completeLoadPlayerActivityJoin(loader);});
			}catch(error:IOError){
				dump("unable to load activity player join");	
			}
		}
		
		// complete load list of volunteers for an activity
		public static function completeLoadPlayerActivityJoin(loader:URLLoader):void{

			//instantiate variables
			var loadedArray:Array = [];
			var decodedArray:Array = [];
			var incoming:String = loader.data;

			if(incoming.search("no result")<0){

				//break down the incoming data into item JSOn Strings
				loadedArray = incoming.split("|");
				
				var length:int = loadedArray.length-1;
				var i:int=0;
				
				//decode array and push it into decoded array
				for( i; i<length; i++){
					
					if(loadedArray[i] != null){
						decodedArray.push(JSON.decode(loadedArray[i]));
					}
				}
				
				MainTimeLine.session.player.volunteer.setPlayerActivityJoin(decodedArray);
				
			}else{
				dump("no activity in database");
			}
			
			MainTimeLine.loadedPlayerActivityJoin = true;
		}
		
		// dump out errors
		public static function dump(message:String):void{
			//MainTimeLine.debugText.text = message;		
		}
	}
}